package com.tpsix.controller;

import com.tpsix.controller.dto.CaptchaDTO;
import com.tpsix.security.Constant;
import com.tpsix.util.R;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(value = "auths", tags = "认证资源")
@RestController
@RequestMapping("auths")
@AllArgsConstructor
public class AuthenticationResource {

    private final RedisTemplate<String, Object> redisTemplate;

    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @GetMapping("/captcha")
    public R<CaptchaDTO> captcha() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        String result = captcha.text();
        String key = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set(Constant.TPSIX_CAPTCHA_KEY + key, result, 2, TimeUnit.MINUTES);

        CaptchaDTO captchaDTO = new CaptchaDTO();
        captchaDTO.setKey(key);
        captchaDTO.setCaptcha(captcha.toBase64());
        return R.ok(captchaDTO);
    }

}
